<template>
  <div class="upload-box">
    <div class="image-upload" :class="{disabled:isDisabled}">
      <el-upload
        :file-list="fileList"
        list-type="picture-card"
        action="#"
        :on-preview="handlePictureCardPreview"
        :limit="2"
        :on-exceed="onExceed"
        :on-remove="handleRemove"
        :http-request="httpRequest"
        :on-change="onChange"
        :before-upload="beforeUpload"
      >
        <i class="el-icon-plus" />
      </el-upload>
      <el-dialog title="图片预览" :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
    </div>
  </div>
</template>

<script>
import cos from '@/utils/cos'
// SecretId: AKID777xwseVFxTp6D3ncGJJ7g2LagjzGWdd
// SecretKey: tc7PVQCmCTWNLCpDNI7i5FDxVrAONTNE
export default {
  props: {
    limit: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      fileList: [
      ],
      dialogImageUrl: '',
      dialogVisible: false,
      showDialog: false, // 控制显示弹层
      imgUrl: ''
    }
  },
  computed: {
    isDisabled() {
      return this.fileList.length >= this.limit
    },
    isAllUploadSuccess() {
      return this.fileList.every(item => item.status === 'success')
    }
  },
  methods: {
    // 上传前的校验
    beforeUpload(file) {
      // console.log('file', file)
      // 1. 限制文件类型 file.type
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      if (!types.includes(file.type)) {
        this.$message.error('上传的图片格式, 必须是jpg, gif, bmp, png的格式!')
        return false
      }
      // 2. 限制文件大小 file.size
      if (file.size / 1024 / 1024 >= 5) {
        this.$message.error('上传头像过大, 超过了5M, 必须5M以内')
        return false
      }
    },
    onChange(file, fileList) {
      this.fileList = [...fileList]
    },
    // 自定义上传
    httpRequest({ file }) {
      const curFile = this.fileList.find(item => item.uid === file.uid)
      curFile.status = 'uploading'
      if (!file) return
      cos.putObject({
        Bucket: 'renzi-1317277673', /* 填入您自己的存储桶，必须字段 */
        Region: 'ap-nanjing', /* 存储桶所在地域，例如ap-beijing，必须字段 */
        Key: +new Date() + file.name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        Body: file, /* 必须，上传文件对象，可以是input[type="file"]标签选择本地文件后得到的file对象 */
        onProgress: function(progressData) {
          // console.log(JSON.stringify(progressData))
          curFile.percentage = progressData.percent * 100
        }
      }, function(err, data) {
        // console.log(err || data)
        if (err) {
          this.$message.success('图片上传失败')
          return
        }
        const url = '//' + data.Location
        curFile.url = url
        setTimeout(() => {
          curFile.status = 'success'
        }, 500)
      })
    },
    handleRemove(file, fileList) {
      // this.fileList = [...fileList]
      this.fileList = this.fileList.filter(item => item.uid !== file.uid)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    onExceed() {
      this.$message.warning('上传最大数')
    }
  }
}
</script>

<style lang="scss" scoped>
.disabled {
  ::v-deep {
    .el-upload--picture-card {
      display: none
    }
  }
}
</style>
